<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Account_func extends LAT_Model {

    function __construct()
    {
        parent::__construct();
		$this->lang->load("validate");
    }


    function create_user($data)
    {
		$r = $this->_ajax();
		$this->load->library('lockout');
		$this->load->helper('string');

		if($this->name_exists($data['name'])) {
			$r['success'] = false;
			$r['msg']['name'] = $this->lang->line('error_name_taken');
			return $r;
		}

		// Check email
		if($this->lockout->num_attempts() >= $this->store->data('setting', 'lockout')) {
			$r['success'] = false;
			$r['msg']['lockout'] = sprintf($this->lang->line('error_locked_out'), strtolower(timespan(time() - $this->store->data('setting', 'lockout_expiration'))));
			return $r;
		} elseif($this->email_exists($data['email'])) {
			$this->lockout->add_attempt($data['email']);
			$r['success'] = false;
			$r['msg']['email'] = $this->lang->line('error_email_taken');
			return $r;
		}

		// Generate password
		if(!$data['salt']) {
			$data['salt'] = random_string('alnum', 10);
		}

		$data['created'] = now();
		$data['password'] = $this->_parse_password($data['password'], $data['salt']);
		$this->db->insert('user', $data);
		$r['user_id'] = $this->db->insert_id();

		return $r;
    }

	// Parses a password
	function _parse_password($pwd, $salt) {
		return md5( $salt . $pwd );
	}

	// Validates username if it doesn't exist
	function name_exists($name) {
		$query = $this->db->select('id')->like('name', $name, 'none')->get('user');
		if($query->num_rows() !== 0) {
			return true;
		}
		return false;
	}

	// Validates email if it doesn't exist
	function email_exists($email) {
		$query = $this->db->select('id')->from('user')->like('email', $email, 'none')->get();
		if($query->num_rows() !== 0) {
			return true;
		}
		return false;
	}
}